package com.wtx.atguigu.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: wtx
 * @createDate: 2020/6/8
 */
public class BIOServer {

    public static void main(String[] args) throws IOException {

        //创建一个线程池
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");

        while (true){
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            //创建一个线程与之通讯
            newCachedThreadPool.execute(()->{
                handler(socket);
            });

        }
    }

    // 与客户端进行通讯的方法
    public static void handler(Socket socket) {

        System.out.println("线程信息: ");
        System.out.println(Thread.currentThread().getId()+" "+Thread.currentThread().getName());
        byte[] bytes = new byte[1024];
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if (read!=-1)
                    System.out.println(new String(bytes,0,read));
                else
                    break;  //读取完毕
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
